import Vuex from "vuex"
import Vue from "vue"
Vue.use(Vuex);
const store = new Vuex.Store({
    state:{
        n:0,
        good:[]
    },
    mutations:{
        add(state,num){
            state.n=parseInt(num)
        },
        saveGoods(state,info){ //点击加入购物车的时候 将商品信息保存到good里面
            var flag = false
                 state.good.some(item=>{
                    if(item.id==info.id){
                      item.count+=info.count;
                        flag=true
                        return true
                      }
                })
                if(!flag){
                    state.good.push(info)
                }
            
            localStorage.setItem("car",JSON.stringify(state.good))  
           
        },
        updateCount(state,info){ //更新购物车里面的数量
            state.good.some(item=>{
                if(item.id == info.id){
                    item.count = parseInt(info.count) ;
                    return true
                }
            });
            localStorage.setItem("car",JSON.stringify(state.good))  
        },
        updateSelect(state,info){ //更新开关状态
            state.good.some(item=>{
                if(item.id == info.id){
                    item.onOff=info.val;
                    return false
                }
            })
            localStorage.setItem("car",JSON.stringify(state.good))  
        },
        remove(state,id){// 删除数据
            state.good.splice(id,1)
            localStorage.setItem("car",JSON.stringify(state.good))  
        }
    },
    getters:{ 
        totalNum(state){
            var n=0;
            state.good.forEach(item=>{
                if(item.onOff){
                    n+= item.count
                }
            })
            return n
        }
    }
})

export default store